package com.ruoyi.flow.auth.security.sso;

import com.ruoyi.flow.auth.security.sso.SsoUsernamePassword;
import com.ruoyi.flow.auth.security.sso.SsoUsernamePasswordProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;
import java.util.Objects;

import static com.google.common.base.Preconditions.checkState;

/**
 * 访问认证器，实现对用户名密码的访问认证
 *
 * @author wtian
 * @version 1.0
 * @since 2018/9/12 14:57
 */
public class SsoAuthenticator {
    private SsoUsernamePasswordProvider provider;

    public SsoAuthenticator(SsoUsernamePasswordProvider provider) {
        this.provider = provider;
    }

    public SecurityContext authenticate(AuthenticationProvider authenticationProvider, Map<String, String[]> parameters) {
        SsoUsernamePassword usernamePassword = provider.getUsernameAndPassword(parameters);
        checkState(Objects.nonNull(usernamePassword), "username and password is null.");
        String username = usernamePassword.getUsername();
        String password = usernamePassword.getPassword();
        checkState(StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password), "username and password is null.");
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationProvider.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return SecurityContextHolder.getContext();
    }
}
